import { execSync } from 'node:child_process'
import { app } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import * as search from './search'
import './db'
import * as shortcut from './common/shortcut'
import * as ipc from './common/ipc'
import * as translate from './translate'
import * as apps from './apps/ipc'
import { createTray } from './utils/tray'

// 在 Windows 上设置控制台编码为 UTF-8，解决中文乱码问题
if (process.platform === 'win32') {
  try {
    // 设置 stdout 和 stderr 的编码为 UTF-8
    if (process.stdout && typeof process.stdout.setDefaultEncoding === 'function') {
      process.stdout.setDefaultEncoding('utf8')
    }
    if (process.stderr && typeof process.stderr.setDefaultEncoding === 'function') {
      process.stderr.setDefaultEncoding('utf8')
    }
    // 尝试设置控制台代码页为 UTF-8 (65001)
    // 注意：这需要在控制台启动时执行，可能不会立即生效
    try {
      execSync('chcp 65001 >nul 2>&1', { shell: 'cmd.exe' })
    } catch {
      // 忽略错误，某些环境可能不支持
    }
  } catch {
    // 忽略设置编码时的错误
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  ipc.register()
  shortcut.register()
  translate.register()
  apps.register()
  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')
  createTray()
  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  search.create()
  
  // 初始化软件列表（异步，不阻塞启动）
  apps.initApps().catch(console.error)

  app.on('activate', () => {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    // if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('will-quit', () => {
  shortcut.unregister()
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
